﻿using AutoMapper;
using B.S.BaseData.Api.Write.Application.Command.Procurements;
using B.S.BaseData.Domain;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;
using MediatR;
using SmartTracking.Domain.ZXL;

namespace B.S.BaseData.Api.Write.Application.CommandHandler.Procurements
{
    public class CreateProcurementCommandHandler : IRequestHandler<CreateProcurementCommand, ApiResult<int>>
    {

        private readonly IBaseRepository<Procurement> _procurementRepository;
        private readonly IBaseRepository<Procurementhead> _procurementhead;
        private readonly IMapper map;

        public CreateProcurementCommandHandler(IBaseRepository<Procurement> procurementRepository, IMapper map, IBaseRepository<Procurementhead> procurementhead)
        {
            _procurementRepository = procurementRepository;
            this.map = map;
            _procurementhead = procurementhead;
        }

        public async Task<ApiResult<int>> Handle(CreateProcurementCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();

            Procurementhead procure = new Procurementhead();

            procure.Purchaser = request.Purchaser;
            procure.PurchaseDate = request.PurchaseDate;
            procure.Sheeptype = request.Sheeptype;
            procure.Category = request.Category;
            procure.Accountingunit = request.Accountingunit;
            procure.Supplier  = request.Supplier;
            procure.Warehouse = request.Warehouse;
            procure.Abstract = request.Abstract;
            procure.Documentnumber = request.Documentnumber;
            procure.Serialnumber = request.Serialnumber;

            await _procurementhead.AddAsync(procure);

            int r = await _procurementRepository.AddRangeAsync(request.procurementList);

            if (r == 0)
            {
                res.Message = "创建采购失败";
                res.Code = ApiEnum.新增失败;
            }
            else
            {
                res.Message = "创建采购成功";
                res.Code = ApiEnum.新增成功;
            }

            return await Task.FromResult(res);

        }
    }
}
